

import java.lang.reflect.Type;

import org.apache.log4j.Logger;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class UserAdapter implements JsonDeserializer<User>, JsonSerializer<User>{
	
	private static Logger logger = Logger.getLogger(UserAdapter.class.getName());
	
	@Override
	public JsonElement serialize(User u, Type typeOfUser, JsonSerializationContext context) {
		JsonObject jsonObject = new JsonObject();
		
		jsonObject.addProperty("email" , u.getUserEmail());
		jsonObject.addProperty("pwd", u.getUserPwd());
		jsonObject.addProperty("id", u.getId());
		jsonObject.addProperty("email" , u.getUserEmail());
		jsonObject.addProperty("password", u.getUserPwd());
		jsonObject.addProperty("surname", u.getSurname());
		jsonObject.addProperty("name", u.getFirstname());
		jsonObject.addProperty("type", u.getMsgType());
		
		jsonObject.addProperty("points", u.getPoints());
		
		return jsonObject;
	}

	@Override
	public User deserialize(JsonElement json, Type typeOfUser, JsonDeserializationContext context) throws JsonParseException {
		
		JsonObject jsonObject = json.getAsJsonObject();
		User u = new User();
		
		try{
			String id = jsonObject.get("id").getAsString();
			String surname = jsonObject.get("surname").getAsString();
			String firstname = jsonObject.get("name").getAsString();
			String userPwd = jsonObject.get("password").getAsString();
			String userEmail = jsonObject.get("email").getAsString();
			String type = jsonObject.get("type").getAsString();
			
			/*
			 * Due to security reasons the points of a User will never be deserialized, for a user could fake a
			 * Json request and register himself with an unlimited number of points 
			 */
//			int points = jsonObject.get("points").getAsInt();
//			u.setPoints(points);
			
			u.setFirstname(firstname);
			u.setMessage(type);
			u.setSurname(surname);
			u.setUserEmail(userEmail);
			u.setUserPwd(userPwd);
			u.setId(id);
			u.setUserEmail(userEmail);
			u.setUserPwd(userPwd);
		}catch(Exception e){
			logger.warn("Incorrect Json Received. Check Property Names. Exception: " + e);
			//In case the Json was incorrect for some reason it will be set null, so that the program can not
			//work with an incorrect object whatsoever
			u = null;
		}
		
		return u;
	}

}
